/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept 'ovl_create_or_link' function
 *
 * Notes:
 *  - We are maintianing Red-Black tree of pid's for Exploit Detection feature.
 *    When process calls 'ovl_create_or_link', we need to correctly handle
 *    this situation and adjust 'off' flag
 *
 * Caveats:
 *  - None
 *
 * Timeline:
 *  - Created: 28.III.2019
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

#include "../../../../../../p_lkrg_main.h"

char p_ovl_create_or_link_kretprobe_state = 0;

static struct kretprobe p_ovl_create_or_link_kretprobe = {
    .kp.symbol_name = "ovl_create_or_link",
    .handler = p_ovl_create_or_link_ret,
    .entry_handler = p_ovl_create_or_link_entry,
    .data_size = sizeof(struct p_ovl_create_or_link_data),
    /* Probe up to 40 instances concurrently. */
    .maxactive = 40,
};


void p_reinit_ovl_create_or_link_kretprobe(void) {

   memset(&p_ovl_create_or_link_kretprobe,0x0,sizeof(struct kretprobe));
   p_ovl_create_or_link_kretprobe.kp.symbol_name = "ovl_create_or_link";
   p_ovl_create_or_link_kretprobe.handler = p_ovl_create_or_link_ret;
   p_ovl_create_or_link_kretprobe.entry_handler = p_ovl_create_or_link_entry;
   p_ovl_create_or_link_kretprobe.data_size = sizeof(struct p_ovl_create_or_link_data);
   p_ovl_create_or_link_kretprobe.maxactive = 40;
}

int p_ovl_create_or_link_entry(struct kretprobe_instance *p_ri, struct pt_regs *p_regs) {

   return 0;
}


notrace int p_ovl_create_or_link_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   if (p_is_ed_task(current)) {
      // Update process
      p_tasks_write_lock(&p_flags);
      if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
         if (p_verify_ovl_create_or_link(p_tmp)) {
#ifdef P_LKRG_TASK_OFF_DEBUG
            p_debug_off_flag_override_on(p_tmp, 30, p_regs);
#endif
            p_set_ed_process_override_on(p_tmp);
         }
      }
      p_ed_validate_current();
      if (p_ed_enforce_pcfi(current, p_tmp, p_regs)) {
         p_print_log(P_LKRG_CRIT,
                "<Exploit Detection> Stack pointer corruption (ROP?) - pCFI violation: process[%s | %d] !!!\n",
                current->comm,task_pid_nr(current));
         p_pcfi_kill_task_by_task(current);
      }
      p_tasks_write_unlock(&p_flags);
   }

   return 0;
}


GENERATE_INSTALL_FUNC(ovl_create_or_link)
